package com.igeek.web;

import com.igeek.domain.Pagination;
import com.igeek.domain.Product;
import com.igeek.service.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author jerryHe
 * @create 2019-10-08 15:59
 */

@WebServlet("/getProductsByCategoryIdServlet")
public class GetProductsByCategoryIdServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        getHistory(request);


        //1.接收cid
        String cid = request.getParameter("cid");
        //获取当前页  假设当前页的参数是page
        String page = request.getParameter("page");
        int nowPage = 1;
        if(page == null){
            nowPage = 1;
        }else{
            nowPage = Integer.parseInt(page);
        }

        //2.调用service
        ProductService service = new ProductService();
        Pagination<Product> pagination = service.findProductsByCidPage(nowPage,12,cid);
        //3.返回结果
        request.setAttribute("pagination",pagination);
        //把cid存入request域中
        request.setAttribute("cid",cid);
        request.getRequestDispatcher("product_list.jsp").forward(request,response);
    }

    private void getHistory(HttpServletRequest request) {
        //显示浏览记录
        //从cookie中取pids
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for (Cookie c: cookies){
                if(c.getName().equals("pids")){
                    //1,29,2,19,17,13,11
                    String pids = c.getValue();
                    ProductService service = new ProductService();
                    List<Product> products = service.findHistoryProducts(pids);
                    request.setAttribute("products",products);
                }
            }
        }
    }
}
